package keeto.com.vn.classified.task;

import java.io.IOException;

import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.request.ChangeAvatarRequest;
import keeto.com.vn.classified.request.UploadPictureRequest;
import keeto.com.vn.classified.response.ChangeAvatarResponse;
import keeto.com.vn.classified.response.UploadPictureResponse;
import keeto.com.vn.classified.ui.MainApplication;
import keeto.com.vn.classified.utils.Base64;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.util.Log;

public class TaskChangeAvatar extends AbstractTask{
	private byte[] Avatar;
	private String Athkey;
	private String Area;

	private boolean uploaded = false;

	public TaskChangeAvatar(ClassifiedListener listener, ClassifiedCore core,
			byte[] avatar, String athkey, String area) {
		super(listener, core);
		Avatar = avatar;
		Athkey = athkey;
		Area = area;
	}

	@Override
	public void run() throws ClientProtocolException, JSONException,
	IOException {
		// TODO Auto-generated method stub
		ChangeAvatarRequest request = new ChangeAvatarRequest();
		request.setArea(Area);
		request.setAthkey(Athkey);
		request.setAvatar(Avatar);

		uploaded = uploadAvatar(request.getAvatar(), request);
		if (uploaded){
			ChangeAvatarResponse response = json.ChangeAvatar(request); 
			for (ClassifiedListener listener : listeners) {
				listener.finishChangeAvatar(response.getReturnCode(), response.getResultmsg());
			}
		}else{
			for (ClassifiedListener mlistener : core.copyAndReconstructListeners(listener)) {
				mlistener.finishChangeAvatar(IProtocol.STATUS_CODE_CONNECTION_TIMEOUT_502,
						null);
			}
		}

	}

	@Override
	public void timeoutCallback() {
		// TODO Auto-generated method stub
		for (ClassifiedListener mlistener : core.copyAndReconstructListeners(listener)) {
			mlistener.finishChangeAvatar(IProtocol.STATUS_CODE_CONNECTION_TIMEOUT_502,
					null);
		}
	}

	private boolean uploadAvatar(byte[] avatarbyte, ChangeAvatarRequest mRequest) throws ClientProtocolException, JSONException, IOException{
		String content = Base64.encodeToString(avatarbyte, false);
		Log.d("Upload file", content);
		UploadPictureRequest request = new UploadPictureRequest();
		request.setAuthKey(MainApplication.getAuthenKey());
		request.setType(1);
		request.setContent(content);
		Log.d("Test", request.toString());
		UploadPictureResponse response = json.uploadPicture(request,content);
		Log.d("Test", "Upload return :" + response.getReturnCode());
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK_200) {
			mRequest.setDisplayPicture(response.getFileName());
			return true;
		}
		return false;
	}
}
